﻿using Compass.Maui.Pages.FinishGoods;

namespace Compass.Maui.ViewModels;

public partial class MainPlansPageViewModel : BaseViewModel
{
    private readonly IMainPlanService _mainPlanService;
    private readonly INavigationService _navigationService;

    public MainPlansPageViewModel(IMainPlanService mainPlanService, INavigationService navigationService)
    {
        _mainPlanService = mainPlanService;
        _navigationService = navigationService;
    }

    public ObservableRangeCollection<MainPlanDto> MainPlanDtos { get; } = new();

    [RelayCommand]
    private async Task GetMainPlanDtosAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }
            try
            {
                MainPlanDtos.ReplaceRange(await _mainPlanService.GetMainPlansAsync(0, Consts.PageSize));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get mainplans:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing = false;
            }
        });
    }

    [RelayCommand]
    private async Task LoadMoreAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }
            try
            {
                MainPlanDtos.AddRange(await _mainPlanService.GetMainPlansAsync(MainPlanDtos.Count, Consts.PageSize));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get mainplans:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing=false;
            }
        });
    }

    [RelayCommand]
    private async Task GoToPackingInfoAsync(MainPlanDto? mainPlanDto)
    {
        await IsBusyFor(async () =>
        {
            //if (mainPlanDto is null) return;
            //await _navigationService.NavigateToAsync(nameof(PackingInfoPage),
            //    new Dictionary<string, object?>
            //    {
            //        {nameof(MainPlanDto),mainPlanDto}
            //    });
        });
    }

}